from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render


# Create your views here.
from .models import Note


def check_login(func):
    def wrap(request, *args, **kwargs):
        if 'username' not in request.session or 'uid' not in request.session:
            # 检查cookies
            c_username = request.COOKIES.get('username')
            c_uid = request.COOKIES.get('uid')
            if not c_username or not c_uid:
                return HttpResponseRedirect('/user/login')
            else:
                # 回写session
                request.session['username'] = c_username
                request.session['uid'] = c_uid
        return func(request, *args, **kwargs)

    return wrap

@check_login
def add_note(request):
    if request.method == 'GET':
        return render(request, 'notebook/add_note.html')
    if request.method == 'POST':
        title = request.POST['title']
        content = request.POST['content']
        user_id = request.session['uid']

        Note.objects.create(title=title,content=content,user_id=user_id)
        return HttpResponse("添加笔记成功")
